<?php
/**
 * Created by JetBrains PhpStorm.
 * User: taoqili
 * Date: 12-7-18
 * Time: 上午11: 32
 * UEditor编辑器通用上传类
 */
class Uploader
{
    private $fileField;            //文件域名
    private $file;                 //文件上传对象
    private $config;               //配置信息
    private $oriName;              //原始文件名
    private $fileName;             //新文件名
    private $pureName;             //新文件名（不包含格式标识）
    public  $fullName;             //完整文件名,即从当前配置目录开始的URL
    private $fileSize;             //文件大小
    private $fileType;             //文件类型
    private $stateInfo;            //上传状态信息,
    private $stateMap = array(    //上传状态映射表，国际化用户需考虑此处数据的国际化
        "SUCCESS" ,                //上传成功标记，在UEditor中内不可改变，否则flash判断会出错
        "文件大小超出 upload_max_filesize 限制" ,
        "文件大小超出 MAX_FILE_SIZE 限制" ,
        "文件未被完整上传" ,
        "没有文件被上传" ,
        "上传文件为空" ,
        "POST" => "文件大小超出 post_max_size 限制" ,
        "SIZE" => "文件大小超出网站限制" ,
        "TYPE" => "不允许的文件类型" ,
        "DIR" => "目录创建失败" ,
        "IO" => "输入输出错误" ,
        "UNKNOWN" => "未知错误" ,
        "MOVE" => "文件保存时出错"
    );

    /**
     * 构造函数
     * @param string $fileField 表单名称
     * @param array $config  配置项
     */
    public function __construct($fileField , $config)
    {
        $this->fileField = $fileField;
        $this->config    = $config;
        $this->stateInfo = $this->stateMap[ 0 ];
    }

    /**
     * 上传图片的主处理方法
     * @param bool $base64
     * @return mixed
     */
    public function upFile($base64 = false)
    {
        //处理base64上传
        if ( "base64" == $base64 ) {
            $content = $_POST[ $this->fileField ];
            $this->base64ToImage( $content );
            return;
        }

        //处理普通上传
        $file = $this->file = $_FILES[ $this->fileField ];
        if ( !$file ) {
            $this->stateInfo = $this->getStateInfo( 'POST' );
            return ['code' => 201, 'msg' => '文件上传有误'];
        }
        if ( $this->file[ 'error' ] ) {
            $this->stateInfo = $this->getStateInfo( $file[ 'error' ] );
            return ['code' => 202, 'msg' => '文件上传有误'];
        }
        if ( !is_uploaded_file( $file[ 'tmp_name' ] ) ) {
            $this->stateInfo = $this->getStateInfo( "UNKNOWN" );
            return ['code' => 203, 'msg' => '文件名称有误'];
        }

        $this->oriName = $file[ 'name' ];
        $this->fileSize = $file[ 'size' ];
        $this->fileType = $this->getFileExt();

        if ( !$this->checkSize() ) {
            $this->stateInfo = $this->getStateInfo( "SIZE" );
            return ['code' => 204, 'msg' => '文件大小有误'];
        }
        if ( !$this->checkType() ) {
            $this->stateInfo = $this->getStateInfo( "TYPE" );
            return ['code' => 205, 'msg' => '文件类型有误'];
        }
        $this->fullName = $this->getFolder() . '/' . $this->getName();
        if ( $this->stateInfo == $this->stateMap[ 0 ] ) {
            if ( !move_uploaded_file( $file[ "tmp_name" ] , $this->fullName ) ) {
                $this->stateInfo = $this->getStateInfo( "MOVE" );
            }
        }
        return ['code' => 200];
    }

    /**
     * 上传excel的主处理方法
     * @return mixed
     */
    public function uploadExcel()
    {
        $file = $this->file = $_FILES[ $this->fileField ];
        if ( !$file ) {
            $this->stateInfo = $this->getStateInfo( 'POST' );
            return ['code' => 201, 'msg' => '文件上传有误'];
        }
        if ( $this->file[ 'error' ] ) {
            $this->stateInfo = $this->getStateInfo( $file[ 'error' ] );
            return ['code' => 202, 'msg' => '文件上传有误'];
        }
        if ( !is_uploaded_file( $file[ 'tmp_name' ] ) ) {
            $this->stateInfo = $this->getStateInfo( "UNKNOWN" );
            return ['code' => 203, 'msg' => '文件名称有误'];
        }

        $this->oriName = $file[ 'name' ];
        $this->fileSize = $file[ 'size' ];
        $this->fileType = $this->getFileExt();

        if ( !$this->checkSize() ) {
            $this->stateInfo = $this->getStateInfo( "SIZE" );
            return ['code' => 204, 'msg' => '文件大小有误'];
        }
        if ( !$this->checkType() ) {
            $this->stateInfo = $this->getStateInfo( "TYPE" );
            return ['code' => 205, 'msg' => '文件类型有误'];
        }
        $this->fullName = $this->getFolder() . '/' . $this->getName();
        if ( $this->stateInfo == $this->stateMap[ 0 ] ) {
            if ( !move_uploaded_file( $file[ "tmp_name" ] , $this->fullName ) ) {
                $this->stateInfo = $this->getStateInfo( "MOVE" );
            }
        }
        return ['code' => 200];
    }

    /**
     * 处理base64编码的图片上传
     * @param $base64Data
     * @return mixed
     */
    private function base64ToImage( $base64Data )
    {
        $img = base64_decode( $base64Data );
        $this->fileName = time() . rand( 1 , 10000 ) . ".png";
        $this->fullName = $this->getFolder() . '/' . $this->fileName;
        if ( !file_put_contents( $this->fullName , $img ) ) {
            $this->stateInfo = $this->getStateInfo( "IO" );
            return;
        }
        $this->oriName = "";
        $this->fileSize = strlen( $img );
        $this->fileType = ".png";
    }

    /**
     * 获取当前上传成功文件的各项信息
     * @return array
     */
    public function getFileInfo()
    {
        $url = str_replace('../', '', $this->fullName);
        list($width, $height, $type, $attr) = getimagesize($this->fullName);
        return array(
            "originalName" => $this->oriName ,
            "name"         => $this->fileName ,
            "url"          => $url ,
            "size"         => $this->fileSize ,
            "type"         => $this->fileType ,
            "state"        => $this->stateInfo,
            "width"        => $width,
            "height"       => $height,
        );
    }

    /**
     * 上传错误检查
     * @param $errCode
     * @return string
     */
    private function getStateInfo( $errCode )
    {
        return !$this->stateMap[ $errCode ] ? $this->stateMap[ "UNKNOWN" ] : $this->stateMap[ $errCode ];
    }

    /**
     * 重命名文件
     * @return string
     */
    private function getName()
    {
        return $this->fileName = $this->getRealName() . $this->getFileExt();
    }

    private function getRealName() {
        return $this->pureName = $_SERVER['REQUEST_TIME'] . rand( 1 , 10000 );
    }
    /**
     * 文件类型检测
     * @return bool
     */
    private function checkType()
    {
        return in_array( $this->getFileExt() , $this->config[ "allowFiles" ] );
    }

    /**
     * 文件大小检测
     * @return bool
     */
    private function  checkSize()
    {
        return $this->fileSize <= ( $this->config[ "maxSize" ] * 1024 );
    }

    /**
     * 获取文件扩展名
     * @return string
     */
    private function getFileExt()
    {
        return strtolower( strrchr( $this->file[ "name" ] , '.' ) );
    }

    /**
     * 按照日期自动创建存储文件夹
     * @return string
     */
    private function getFolder()
    {
        $pathStr = $this->config[ "savePath" ];
        if ( strrchr( $pathStr , "/" ) != "/" ) {
            $pathStr .= "";
        }
        if(!$this->config['simpleFolder']) {
            $pathStr .= date( "Ymd" );
        }
        //echo $pathStr;
        if ( !file_exists( $pathStr ) ) {
            if ( !mkdir( $pathStr , 0777 , true ) ) {
                return false;
            }
        }

        return $pathStr;
    }

     public function smart_resize_image( $width, $height, $proportional = false) 
     {
        $file = $this->fullName;
        $output = dirname($file).'/'.$this->pureName.'_thumb'.$this->fileType;
        if ( $height <= 0 && $width <= 0 ) return false;
        # Setting defaults and meta
        $info                         = getimagesize($file);
        $image                        = '';
        $final_width                  = 0;
        $final_height                 = 0;
        list($width_old, $height_old) = $info;

        # Calculating proportionality
        if ($proportional) {
          if      ($width  == 0)  $factor = $height/$height_old;
          elseif  ($height == 0)  $factor = $width/$width_old;
          else                    $factor = min( $width / $width_old, $height / $height_old );

          $final_width  = round( $width_old * $factor );
          $final_height = round( $height_old * $factor );
        }
        else {
          $final_width = ( $width <= 0 ) ? $width_old : $width;
          $final_height = ( $height <= 0 ) ? $height_old : $height;
        }

        # Loading image to memory according to type
        switch ( $info[2] ) {
          case IMAGETYPE_GIF:   $image = imagecreatefromgif($file);   break;
          case IMAGETYPE_JPEG:  $image = imagecreatefromjpeg($file);  break;
          case IMAGETYPE_PNG:   $image = imagecreatefrompng($file);   break;
          default: return false;
        }
        
        # This is the resizing/resampling/transparency-preserving magic
        $image_resized = imagecreatetruecolor( $final_width, $final_height );
        if ( ($info[2] == IMAGETYPE_GIF) || ($info[2] == IMAGETYPE_PNG) ) {
          $transparency = imagecolortransparent($image);

          if ($transparency >= 0) {
            $transparent_color  = imagecolorsforindex($image, $trnprt_indx);
            $transparency       = imagecolorallocate($image_resized, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
            imagefill($image_resized, 0, 0, $transparency);
            imagecolortransparent($image_resized, $transparency);
          }
          elseif ($info[2] == IMAGETYPE_PNG) {
            imagealphablending($image_resized, false);
            $color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127);
            imagefill($image_resized, 0, 0, $color);
            imagesavealpha($image_resized, true);
          }
        }
        imagecopyresampled($image_resized, $image, 0, 0, 0, 0, $final_width,
            $final_height, $width_old, $height_old);
//         imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
//             $targ_w,$targ_h,$_POST['w'],$_POST['h']);
        # Taking care of original, if needed
//        if ( $delete_original ) {
//          if ( $use_linux_commands ) exec('rm '.$file);
//          else @unlink($file);
//        }
        # Writing image according to type to the output destination
        switch ( $info[2] ) {
          case IMAGETYPE_GIF:   imagegif($image_resized, $output);    break;
          case IMAGETYPE_JPEG:  imagejpeg($image_resized, $output);   break;
          case IMAGETYPE_PNG:   imagepng($image_resized, $output);    break;
          default: return false;
        }
        return str_replace('../', '', $output);
    }
     public static function crop_image( $file, $width, $height, $x, $y )
     {
         $targ_w = $targ_h = 150;
         $root   = '/var/www/html/zft/public/uploads/'; 
         $file   = $root.str_replace('//','/', $file);
         $info   = getimagesize($file);

        switch ( $info[2] ) {
          case IMAGETYPE_GIF:
              $image = imagecreatefromgif($file);
              $fileType = '.gif';
              break;
          case IMAGETYPE_JPEG:
              $image = imagecreatefromjpeg($file);
              $fileType = '.jpg';
              break;
          case IMAGETYPE_PNG:
              $image = imagecreatefrompng($file);
              $fileType = '.png';
              break;
          default: return false;
        }
        $image_resized = imagecreatetruecolor( $targ_w, $targ_h );
        $output = dirname($file).'/'. rand( 1 , $_SERVER['REQUEST_TIME'] ).$fileType;
        imagecopyresampled($image_resized, $image, 0, 0,$x,
            $y,$targ_w, $targ_h , $width, $height);
        switch ( $info[2] ) {
          case IMAGETYPE_GIF:   imagegif($image_resized, $output);    break;
          case IMAGETYPE_JPEG:  imagejpeg($image_resized, $output);   break;
          case IMAGETYPE_PNG:   imagepng($image_resized, $output);    break;
          default: return false;
        }
         return str_replace($root, '', $output);
     }


}